﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mystery.SharePoint
{
    /// <summary>
    /// Performs management of the user configuration on the site
    /// </summary>
    class UserManagementStep: ISiteManagementStep
    {
        public bool Execute(Microsoft.SharePoint.SPSite root, Microsoft.SharePoint.SPSite site)
        {
            if (site.Features.IsActivated(FeatureName.SynchronizeAdmins) == true)
            {
                root.SynchronizeAdmins(site);
            }
            if (site.Features.IsActivated(FeatureName.SynchronizeVisitors) == true)
            {
                root.SynchronizeVisitors(site);
            }

            if (site.Owner.LoginName.Equals(root.Owner.LoginName) == false)
            {
                if (site.Features.IsActivated(FeatureName.OwnerRemainsAdmin) == false)
                {
                    if (site.RootWeb.AssociatedOwnerGroup != null)
                    {
                        // if the original owner shouldn't be the site admin, make sure they are a normal owner instead
                        if (site.RootWeb.AssociatedOwnerGroup.Users.FindByLogin(site.Owner.LoginName) == null)
                        {
                            site.RootWeb.AssociatedOwnerGroup.Users.Add(root.Owner.LoginName);
                        }
                    }
                    // the user should always be found if the synchronization code a few lines up worked as expected
                    site.Owner = site.RootWeb.SiteUsers.FindByLogin(root.Owner.LoginName);
                }
            }
            return true;
        }
    }
}
